package com.winter.service;

import com.google.common.base.Strings;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winter.mapper.CompanyUserMapper;
import com.winter.mapper.DictEntryMapper;
import com.winter.mapper.FinContentLikeInfoMapper;
import com.winter.mapper.FinFavInfoMapper;
import com.winter.mapper.FinOnlineMapper;
import com.winter.mapper.IcompanyCardMapper;
import com.winter.mapper.UserInfoMapper;
import com.winter.mapper.UserMapper;
import com.winter.model.DictEntry;
import com.winter.model.FinContentLikeInfo;
import com.winter.model.FinOnline;
import com.winter.model.IcompanyCard;
import com.winter.model.UserInfo;
import com.winter.util.Constants;
import com.winter.util.Result;
import com.winter.util.ResultCode;

@Service
@Transactional
public class FinOnlineService {

    @Autowired
    public FinOnlineMapper finOnlineMapper;
    @Autowired
    public FinFavInfoMapper finFavInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private DictEntryMapper dictEntryMapper;

    /**
     * 点赞
     */
    @Autowired
    private FinContentLikeInfoMapper finContentLikeInfoMapper;

    @Autowired
    private IcompanyCardMapper icompanyCardMapper;

    /**
     * 查询报价平台线上列表
     *
     * @return List
     */
    public Result queryPageList(Integer pageNumber, Integer pageSize, String direction, String pattern, String deadline, String profit, String userNo, String sortName, String sort) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        PageHelper.startPage(pageNumber, pageSize, false);
        List<FinOnline> finOnlineList = finOnlineMapper.selectPageList(direction, pattern, deadline, profit, sortName, sort);

        if (finOnlineList.size() > 0) {
            for (FinOnline finOnline : finOnlineList) {
                String photoPath = null;
                String photoType = finOnline.getPhotoType();
                if (!Strings.isNullOrEmpty(photoType)) {
                    if (photoType.equals("0")) {
                        // 获取创建人头像
                        String createUser = finOnline.getCreateUser();
                        UserInfo userInfo = userInfoMapper.selectByUserNo(createUser);
                        if (userInfo != null) {
                            String custImgUrl = userInfo.getCustImgUrl();
                            if (!Strings.isNullOrEmpty(custImgUrl)) {
                                finOnline.setAvatar(userInfo.getCustImgUrl());
                            }
                        } else {
                            //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                            //(int)(1+Math.random()*(10-1+1))
                            int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                            photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                            finOnline.setAvatar(photoPath);
                        }
                    } else {
                        //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                        //(int)(1+Math.random()*(10-1+1))
                        int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                        photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                        finOnline.setAvatar(photoPath);
                    }
                }

                finOnline.setIsLike("0");
                finOnline.setFinFavStatus("0");
                if (!Strings.isNullOrEmpty(userNo)) {
                    // 点赞
                    List<FinContentLikeInfo> isLike = finContentLikeInfoMapper.getIsLike(finOnline.getId(), "1", "1", userNo);
                    if (isLike.size() > 0) {
                        finOnline.setIsLike("1");
                    }
                    // 收藏
                    Long aLong = finFavInfoMapper.get(finOnline.getId(), "1", 1, userNo);
                    if (aLong > 0) {
                        finOnline.setFinFavStatus("1");
                    }
                }
                getTypeName(finOnline);
            }
        }

        PageInfo<FinOnline> pageInfo = new PageInfo<>(finOnlineList);
        return Result.success(pageInfo);
    }

    public void getTypeName(FinOnline finOnline) {
        String couParty = "";
        String fundMode = "";

        DictEntry dictEntry = dictEntryMapper.get("DC_MONEY_DIRECTION", finOnline.getDirect());
        if (dictEntry != null) {
            finOnline.setDirect(dictEntry.getDictname());
        }
        // 对手
        if (!Strings.isNullOrEmpty(finOnline.getCouParty())) {
            String[] split = finOnline.getCouParty()
                                      .split(",");
            for (int i = 0; i < split.length; i++) {
                DictEntry dc_opponent = dictEntryMapper.get("DC_OPPONENT", split[i]);
                if (split.length - 1 == i) {
                    couParty += dc_opponent.getDictname();
                } else {
                    couParty += dc_opponent.getDictname() + ",";
                }
            }
        }

        if (!Strings.isNullOrEmpty(finOnline.getFundMode())) {
            String[] split = finOnline.getFundMode()
                                      .split(",");
            // DC_ONLINE_MODEL  = 模式
            for (int i = 0; i < split.length; i++) {
                DictEntry dc_opponent = dictEntryMapper.get("DC_ONLINE_MODEL", split[i]);
                if (split.length - 1 == i) {
                    fundMode += dc_opponent.getDictname();
                } else {
                    fundMode += dc_opponent.getDictname() + ",";
                }
            }
        }
        finOnline.setFundMode(fundMode);
        finOnline.setCouParty(couParty);
    }

    /**
     * 新增线上报价
     */
    public Result insertFin(FinOnline fin) {
        if (null != fin) {
            if (Strings.isNullOrEmpty(fin.getCreateUser())) {
                return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
            }
            if (Strings.isNullOrEmpty(fin.getDirect())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择方向");
            }
            if (Strings.isNullOrEmpty(fin.getTermEnd())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择期限");
            }
            if (Strings.isNullOrEmpty(fin.getFundMode())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择模式");
            }
            if (Strings.isNullOrEmpty(fin.getMonEnd()) && Strings.isNullOrEmpty(fin.getMonBeg())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入金额");
            }
            if (Strings.isNullOrEmpty(fin.getRateEnd()) && Strings.isNullOrEmpty(fin.getRateBeg())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入利率");
            }
            if (Strings.isNullOrEmpty(fin.getContact())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入联系方式");
            }

            UserInfo userInfo = userInfoMapper.selectByUserNo(fin.getCreateUser());
            String orgNo = userInfo.getOrgNo();
            IcompanyCard icompanyCard = icompanyCardMapper.selectByPrimaryKey(Long.valueOf(orgNo));
            // 公司信息
            fin.setUserName(userInfo.getUserName());
            fin.setUserCom(icompanyCard.getCompanyName());
            fin.setUserDepart(userInfo.getDepart());
            fin.setUserPost(userInfo.getPost());
            fin.setUserEmail(userInfo.getOrgEmail());
            fin.setUserQq(userInfo.getQq() + "");
            fin.setUserWx(userInfo.getWxNo());
            fin.setTopTime(new Date());

            // 配置数据
            fin.setUpdateUser(fin.getCreateUser());
            fin.setPhotoType("0");
            fin.setStas("3");
            fin.setCreatetime(new Date());
            fin.setUpdatetime(new Date());
            fin.setCommentCount(new BigDecimal("0"));
            fin.setFavCount(new BigDecimal("0"));
            fin.setLikeCount(new BigDecimal("0"));
            fin.setCommentFlag("1");
            fin.setLikeFlag("1");
            fin.setReplayFlag("1");
            fin.setIsvalid("1");
            fin.setAuditing("0");
            fin.setPhotoType("0");
            fin.setInfoSrc("0");
            int i = finOnlineMapper.insertSelective(fin);
            if (i > 0) {
                return Result.success("添加成功");
            } else {
                return Result.failure(ResultCode.INSERT_ERROR);
            }
        } else {
            return Result.success("发布线上参数为空");
        }

    }

    /**
     * 根据Id查询 发布的线上报价信息
     */
    public Result queryFinId(Long id, String userNo) {
        FinOnline finOnline = finOnlineMapper.selectByPrimaryKey(id);
        // 获取字典名称
        getTypeName(finOnline);
        finOnline.setIsLike("0");
        finOnline.setFinFavStatus("0");
        if (null != finOnline && !Strings.isNullOrEmpty(userNo)) {
            // 1  = 代表线上 收藏
            Long count = finFavInfoMapper.get(id, "1", 1, userNo);
            if (count > 0) {
                finOnline.setFinFavStatus("1");
            }
            // 点赞
            List<FinContentLikeInfo> isLike = finContentLikeInfoMapper.getIsLike(finOnline.getId(), "1", "1", userNo);
            if (isLike.size() > 0) {
                finOnline.setIsLike("1");
            }
        }
        return Result.success(finOnline);
    }

    /**
     * 修改报价
     */
    public Result updateFinOnline(FinOnline finOnline) {
        if (Strings.isNullOrEmpty(finOnline.getCreateUser())) {
            return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (finOnline.getId() != null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "主键id不能为空");
        }
        if (null == finOnline.getDirect()) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择方向");
        }
        if (Strings.isNullOrEmpty(finOnline.getTermEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择期限");
        }
        if (Strings.isNullOrEmpty(finOnline.getFundMode())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择模式");
        }
        if (Strings.isNullOrEmpty(finOnline.getMonEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入金额");
        }
        if (Strings.isNullOrEmpty(finOnline.getRateEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入利率");
        }
        if (Strings.isNullOrEmpty(finOnline.getContact())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入联系方式");
        }
        finOnline.setUpdatetime(new Date());
        finOnline.setUpdateUser(finOnline.getCreateUser());
        finOnlineMapper.updateByPrimaryKeySelective(finOnline);
        return Result.success("修改成功");
    }
}
